import React from 'react'
// ===================================================================== Temp
import SearchForm from '#cpt/temp/SearchForm'
import Table from '#cpt/temp/Table'
import Controls from '#cpt/temp/Controls'
import SpecCode from '#tp/specCode'
import Cols from '#private/cols'
import SubmitForm from '#cpt/temp/SubmitForm'
// ===================================================================== global declare
const { $fn, $Lazy, $http } = window
// ===================================================================== private component
const Box 					= $Lazy.load(()=>import('#tp/box/box'))
const $cache 				= $Lazy.file(()=>import('#private/cache-api'))
const $time 				= $Lazy.file(()=>import('@com/utils/time'))
const AlreadyEntryTable		= $Lazy.state(()=>import('./already-entry-table'))
const ProjectDetailsTable	= $Lazy.state(()=>import('./project-details-table'))
const ImgEdit 				= $Lazy.state(()=>import('../../basicInfo-entry/cpt/img-edit'))
const ControlModal 			= $Lazy.state(()=>import('./control-modal'))
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		pag: {},
		selectedKeys: [],
		// 搜索表单列表
		forms: [
			{ label: '条码号',		name: 'spec_code' },
			{ label: '标本箱号',		name: 'box_num_id',				type: 'select', 	onValue: ({rows})=>{this.model.box_num=rows?.name}},
			{ label: '第三方条码',	name: 'third_spec_code' },
			{ label: '录入时间',		names: ['start_at','end_at'], 	type:'date-range', name: 'jz-time' },
			{ label: '医院名称',		name: 'hosp_id',				type: 'select', 	loading:true,	onValue: ({rows})=>{this.model.hosp_name=rows?.name}},
			{ label:' ', 			tag: '仅显示有图',	name: 'view_pic',		type: 'checkbox', colon:false, onValue: ({value})=>{this.setState({view_pic:value})}},
		],
		formData: [
			{ label: '医院名称',			name: 'hosp_name', 			full:true, 		disabled: true,	p:' '},
			{ label: '条码号',			name: 'spec_code',			half:true,		disabled: true,	p:' ',		itemClassName:'doubleInProSpec'},
			{ label: '是否记忆项目',		name: 'memory_project',		width:'30%',		type: 'checkbox',	style:{marginLeft:10},
				onValue:({value})=>{
					if(!value){
						this.memoryKindId = []
					}
				},
			},
			{ label: '选择项目',			name: 'project_id',  		full:true, 		autoFocus:true,	type: 'select-table',	loading:true, disabled: true, itemClassName: 'entryEroject', cols:Cols['specimenkindSelect'],	
				onValue:({value})=>{this.addProject(value)}, 	isKeydown: 'kind'
			},
		],
		specData: {},
		// imageVisible: false,
		tabsData:[],
		memoryData:[]
	}
	model = {}
	memoryKindId = []
	componentDidMount(){
		const {spec_code} = $fn.query()
		this.getSelect()
		const { forms } = this.state
		if(spec_code){
			this.model.spec_code = spec_code
			forms[0].value = spec_code
		}
		this.status = this.props.status
		this.tableFetch()
	}
	
	tableFetch = () => {
		this.onTime()
		this.entryTableFetch()
	}
	
	onTime = reset => {
		 $time.then(f=>{
			const arr = f.duration['2-0-24']()
			this.resetModel = { start_at: arr[0], end_at: arr[1], 'jz-time':arr }
			this.model = {...this.model,...this.resetModel}
			this.fetch()
		})
	}
	// 获取下拉数据
	getSelect = () => {
		const { forms, formData } = this.state
		
		$cache.then( async f => {
			// 医院
			$fn.setRow( forms, 'hosp_id',  await f.getCache({ api:'hospital' }))
			// 标本箱号
			$fn.setRow( forms, 'box_num_id', await f.getCache({ api:'box/select3', param:{limit:10000} }) )
			// 选择项目
			$fn.setRow( formData, 'project_id', await f.getCache({ api:'specimenkindSelect' }) )
			//
			this.setState({ forms, formData })
		})
	}
	// paging
	fetch = ()  => $fn.fetch.call(this,'specimen/itemlists', { param: {double_status: this.status},isIndex:true })
	// 表单
	cols = [
		{ title: '条码号', 		dataIndex: 'spec_code',  			...SpecCode(),  			sorter:true },
		{ title: '医院名称', 	dataIndex: 'hosp_name', 			 width:200 },
		{ title: '标本箱号', 	dataIndex: 'box_num',				...$fn.table.exp_num,	 },
		{ title: '采集时间', 	dataIndex: 'coll_time',  			...$fn.table.time,  		sorter:true },
		{ title: '采集类型', 	dataIndex: 'collect_type_name',  	width:100  },
		{ title: '录入时间', 	dataIndex: 'arrival_time',  		...$fn.table.time,			sorter:true, },
		{ title: '第三方来源', 	dataIndex: 'third_source_type_name', width:150 },
		{ title: '第三方条码', 	dataIndex: 'third_spec_code', 		 width:150 },
		{ title: '第三方医院', 	dataIndex: 'third_hosp_name', 		 width:150 },
	]
	
	controls = () => {
		return [
			Controls.back.call(this,{refresh:true} ),   														// 返回
		]
	}
	controls1 = () => {
		const {specData} = this.state
		return [
			Controls.click.call(this, '保存', ()=>{
				const { memory_project } = this.formRef.getValue()
				if(memory_project){
					this.memoryKindId = this.projectTableRef.state.data.map(v=>v.kind_id)
				}else{
					this.memoryKindId = []
				}
				this.setState({memoryData:memory_project?this.projectTableRef.state.data:[]})
				const { uuid } = specData
				$http.submit(null,'specimen-kind-record/saveKind',{ param: {spec_id:uuid,double_status:this.status}, loadingText:`保存中`}).then(data=>{
					$fn.msg.success('保存成功')
					this.clear()
					// this.setState({imageVisible:false})
					this.fetch().then(data=>{
						if(+this.entryType === 1){
							const rows = this.state.data[this.index]
							if(rows){
								this.setState({selectedKeys:[rows.index]})
								this.onRow(rows.spec_code,true,true)
							}
						}
					})
					this.entryTableFetch(true)
				})
			},{code: 'F8', disabled:!$fn.hasObject(specData)} ),
			// Controls.click.call(this, '查看图片', ()=>{
			// 	this.setState({imageVisible:true})
			// },{ disabled: !specData.image } )
		]
		
	}
	// 新增查看自然项目 2022年12月7日15:57:25 敖得卓
	controls2 = () => {
		const {specData} = this.state
		return [
			Controls.click.call(this, '查看自然项目', () => this.modal.open(specData, this.props.status),{code: 'F9', disabled:!$fn.hasObject(specData)} ),
		]
		
	}
	
	// 添加项目
	addProject = value => {
		const {uuid,spec_code} = this.state.specData
		$http.submit(null,'specimen-kind/batchadd',{ param:{ kind_ids:[value], spec_id:uuid,spec_code,double_status:this.status}, loadingText:`添加中`}).then(data=>{
			$fn.msg.success('添加成功')
			this.projectTableRef.fetch({spec_id:uuid,spec_code})
			this.formRef.reset(['project_id'])
		}).catch(() => {
			this.formRef.reset(['project_id'])
		})
		this.itemFocus()
	}
	// 选择项目光标聚焦
	itemFocus = () => {
		setTimeout(() => {
			document.querySelector('.entryEroject .ant-select-selection-search-input').focus()
		}, 500)
	}
	
	// 表格的点击事件
	onRow = (spec_code,showImg=false,isMemory=false)=> {
		const { memory_project } = this.formRef.getValue()
		$http.submit(null, 'specimen/getspeccodeInfo', { param:{spec_code} } ).then(data=>{
			if($fn.hasObject(data)){
				$fn.disabledRows(this.state.formData, 'project_id', false)
				const { hosp_name, spec_code, uuid} = data
				this.formRef.setValue({ hosp_name, spec_code })
				if(memory_project && isMemory && $fn.hasArray(this.memoryKindId) && +this.entryType===1 ){		// 添加记忆项目
					$http.submit(null,'specimen-kind/batchadd',{ param:{ kind_ids:this.memoryKindId, spec_id:uuid,spec_code,double_status:this.status}, loadingText:`添加中`}).then(data=>{
						$fn.msg.success.then(f=>f.success(`添加成功`))
						this.projectTableRef.fetch({spec_id:uuid,spec_code},true)
					}).catch(()=>{
						this.projectTableRef.fetch({spec_id:uuid,spec_code},true)
					})
				}else{
					this.projectTableRef.fetch({spec_id:uuid,spec_code})
				}
				if(+this.entryType===1 && showImg && data.image){
					// this.setState({specData:data,imageVisible:true})
					this.setState({specData:data})
				}else {
					// this.setState({specData:data,imageVisible:false})
					this.setState({specData:data})
				}
			}
			this.itemFocus()
		})
	}
	
	entryTableFetch = (savePage) =>{
		clearInterval(this.timer)
		this.timer = setInterval(() => {
			if (this.entryTableRef && this.searchFormRef) {
				clearInterval(this.timer)
				const searchForm = this.searchFormRef.getValue()
				const {start_at,end_at,box_num,hosp_name} = this.model
				const { sort_type, sort, current } = this.entryTableRef.model
				this.entryTableRef.model = {...searchForm, start_at, end_at, double_status:+this.status, sort_type,sort,box_num,hosp_name}
				if(savePage){
					this.entryTableRef.model.current = current
				}
				this.entryTableRef.fetch()
			} 
		}, 200)
	}
	
	formReset = () => {
		this.searchFormRef.form.resetFields()
		this.setState({selectedKeys:[], specData:{}})
		$time.then(f=>{
			const arr = f.duration['2-0-24']()
			this.resetModel = { start_at: arr[0], end_at: arr[1], 'jz-time':arr }
			this.model = $fn.copy(this.resetModel)
			this.searchFormRef.setValue(this.resetModel)
			this.fetch()
			this.entryTableFetch()
			this.formRef.reset()
			this.projectTableRef.reset()
		})
	}
	clearSelect = () => {
		this.setState({selectedKeys:[]})
	}
	clear = () => {
		$fn.disabledRows(this.state.formData, 'project_id', true)
		this.setState({selectedKeys:[],specData:{}})
		this.entryTableRef.clearSelect()
		this.projectTableRef.reset()
	}
	
	render(){
		const { specData, memoryData } = this.state
		return (
			<>
				<div className='fv ex'>
					{/* 搜索 */}
					{ SearchForm.call(this, {timeStr:'2-0-24',
						onSubmit:() => {
							this.model.current=1
							this.clear()
							this.formRef.reset()
							this.fetch()
							this.entryTableFetch()
						},
						onReset: () => this.formReset()
					})}
					{/* 表格 */}
					<div className='fx h'>
						<div className='h fx ex rel'>
							<Box title="待录入" className='ex' flex contentClassName='rel fv pt10'>
								{ Table.call(this, { type:1, sort:true, isIndex:true, 
									onRow: ({spec_code},index) => {
										this.index = index
										this.entryType = 1
										this.entryTableRef.clearSelect()
										this.onRow(spec_code)
									},
								} )}
							</Box>
							<Box title="已录入" className='ex' flex contentClassName='rel fv pt10'>
								<AlreadyEntryTable onRef={ ref => this.entryTableRef = ref }
									onRow={this.onRow}
									onFetch={() => this.entryTableFetch()}
									clearSelect={this.clearSelect} 
									setEntryType={()=>this.entryType = 2}
								/>
							</Box>
							{/* 显示图片 */}
							{/*this.state.imageVisible &&
								<ImgEdit onRef ={ref=>this.imgEditRef=ref} src={specData?.image} close={()=>{this.setState({imageVisible:false})}}/>*/}
						</div>
						<div className='fv h'>
							<Box title={+this.status===1?'第一次录入':'第二次录入'} className='fx' flex contentClassName='pt10 proForm' controls={this.controls1()}>
								<div className='' style={{width:660}}>{SubmitForm.call(this,{ labelWidth:'s6'})}</div>
							</Box>
							<Box title="项目明细" className='ex' style={{minHeight:280}} flex contentClassName='rel fv pt10' controls={this.controls2()}>
								<ProjectDetailsTable onRef={ ref => this.projectTableRef = ref } specData = {specData} status={this.status} entryType={this.entryType} memoryData={memoryData} />
							</Box>
						</div>
					</div>
				</div>
				<div style={{minHeight: 250, maxHeight: 250}}>
					<ImgEdit noBg src={specData?.image} doubleClick/>
				</div>
				<ControlModal onRef={ref=>this.modal=ref} />
			</>
		)
	}
}

export default Index